//给你一个二叉树的根节点 root ，按 任意顺序 ，返回所有从根节点到叶子节点的路径。 
//
// 叶子节点 是指没有子节点的节点。 
// 
//
// 示例 1： 
//
// 
//输入：root = [1,2,3,null,5]
//输出：["1->2->5","1->3"]
// 
//
// 示例 2： 
//
// 
//输入：root = [1]
//输出：["1"]
// 
//
// 
//
// 提示： 
//
// 
// 树中节点的数目在范围 [1, 100] 内 
// -100 <= Node.val <= 100 
// 
// Related Topics 树 深度优先搜索 字符串 回溯 二叉树 
// 👍 809 👎 0

package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;

/**
 * [257]二叉树的所有路径
 */
public class BinaryTreePaths {
    public static void main(String[] args) {
        Solution solution = new BinaryTreePaths().new Solution();
        TreeNode head = new TreeNode(1);
        TreeNode headLeft = new TreeNode(2);
        TreeNode headRight = new TreeNode(3);
        head.left = headLeft;
        head.right = headRight;
        TreeNode headLeftRight = new TreeNode(5);
        headLeft.right = headLeftRight;
        List<String> result = solution.binaryTreePaths(head);
        System.out.println(result);
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

public static class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    private List<String> result = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        search(root, new ArrayList<>());
        return result;
    }

    private void search(TreeNode node, List<Integer> path) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        if (node.left == null && node.right == null) {
            String route = parsePath(path);
            result.add(route);
        } else {
            search(node.left, path);
            search(node.right, path);
        }
        path.remove(path.size()-1);
    }

    private String parsePath(List<Integer> path) {
        String result = Integer.toString(path.get(0));
        for (int i = 1; i < path.size(); i++) {
            result = result + "->" + path.get(i);
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}